package com.orange.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.orange.handler.AuthOrgUserService;
import com.orange.modules.bean.SessionUser;
import com.orange.modules.entity.manage.AuthOrgUser;
import com.orange.util.Hash;
import com.orange.util.ReturnCode;

@Controller
@RequestMapping("/orguser")
public class AuthOrgUserController extends BaseController{

	private static final Logger logger = Logger.getLogger(AuthOrgUserController.class);
	
	@Autowired
	private AuthOrgUserService authOrgUserService;
	
	/**
	 * 用户登录
	 * @param map
	 * @return
	 */
	@RequestMapping(value="/login" ,produces = MediaType.TEXT_HTML_VALUE+";charset=UTF-8", method=RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<String> login(HttpServletRequest request,
										HttpServletResponse response ,
										@RequestBody Map<String ,String> map
			){
		try {
			String account=map.get("account");
			if(StringUtils.isBlank(account)){
				return toResponse(null,ReturnCode.PARAMETER_NOT_NULL,"account不可为空");
			}
			String password=map.get("password");
			if(StringUtils.isBlank(password)){
				return toResponse(null,ReturnCode.PARAMETER_NOT_NULL,"password不可为空");
			}
			AuthOrgUser a=authOrgUserService.getAuthOrgUserByAccount(account,"4");
			if(null==a){
				return toResponse(null,ReturnCode.USERNAME_OR_PASSWORD_FALSE,"用户名或密码错误");
			}
			String newPassw=Hash.sha2InHex(password);
			if(!newPassw.equals(a.getPassword())){
				return toResponse(null,ReturnCode.USERNAME_OR_PASSWORD_FALSE,"用户名或密码错误");
			}
			//String nowTime=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
			request.getSession().setAttribute(SessionUser.SESSION_USER_KEY, a.getPid());
			request.getSession().setMaxInactiveInterval(1800);
			return toResponse(null,ReturnCode.SUCCESS,"登录验证成功");
		} catch (Exception e) {
			logger.error("登录异常", e);
			return toResponse(null,ReturnCode.FAIL,"登录异常");
		}
	}
}
